package org.bitmap.mm.util;

import java.io.File;

import android.content.Context;

/**
 * 单纯的下载图片线程，图片如果本地存在了就不再重复下载了.
 * @author iWei
 */
class SimpleBitmapTask extends Thread {

	private String imageUrl;
	private LoveBitmapManager mLoveBitmapManager;
	private OnFetchCompleteListener mCallback;
	private OnAllFetchCompleteListener mAllCallback;
	
	public SimpleBitmapTask(LoveBitmapManager bitmanager, String imgURL,OnFetchCompleteListener callback) {
		imageUrl = imgURL;
		mLoveBitmapManager = bitmanager;
		mCallback = callback;
	}
	/**
	 * 本地是否已经存在图片文件
	 * @return
	 */
	public boolean hasBitmap(){
		if(mLoveBitmapManager==null)return false;
		
		final File cacheDir = FileLove.getExternalCacheDir(mLoveBitmapManager.getContext());
		if (!cacheDir.exists()) {
			cacheDir.mkdir();
		}

		final File cachedFile = new File(cacheDir,
				FileLove.hashKeyForDisk(imageUrl));
		if (cachedFile.exists()) {
			return true;
		}else{
			return false;
		}
	}
	/**
	 * 
	 * 静态方法，检查指定URL图片是否已经下载到本地
	 * @param ctx
	 * @param url
	 * @return
	 */
	public static final boolean hasBitmap(Context ctx,String url){
		final File cacheDir = FileLove.getExternalCacheDir(ctx);
		if (!cacheDir.exists()) {
			cacheDir.mkdir();
		}
		final File cachedFile = new File(cacheDir,
				FileLove.hashKeyForDisk(url));
		if (cachedFile.exists()) {
			return true;
		}else{
			return false;
		}
	}
	@Override
	public void run() {

		File mFile = HttpLove.downloadBitmapToFile(
				mLoveBitmapManager.getContext(), imageUrl);
		if(mCallback!=null){
			mCallback.onFetchComplete(imageUrl,mFile);
		}
		System.gc();
	}
	public OnAllFetchCompleteListener getOnAllFetchCompleteListener() {
		return mAllCallback;
	}
	public void setOnAllFetchCompleteListener(OnAllFetchCompleteListener mAllCallback) {
		this.mAllCallback = mAllCallback;
	}

}
